// import { ElMessage, ElMessageBox } from 'element-plus'

// 加载状态管理
export class LoadingManager {
  private static loadingCount = 0
  private static loadingInstance: any = null

  static show(text = '加载中...') {
    this.loadingCount++
    if (!this.loadingInstance) {
      // 这里可以集成具体的loading组件
      console.log(`Loading: ${text}`)
    }
  }

  static hide() {
    this.loadingCount--
    if (this.loadingCount <= 0) {
      this.loadingCount = 0
      if (this.loadingInstance) {
        this.loadingInstance.close()
        this.loadingInstance = null
      }
      console.log('Loading hidden')
    }
  }

  static hideAll() {
    this.loadingCount = 0
    if (this.loadingInstance) {
      this.loadingInstance.close()
      this.loadingInstance = null
    }
  }
}

// 消息提示工具
export class MessageUtils {
  static success(message: string) {
    console.log(`✅ ${message}`)
    // 这里可以集成具体的消息组件
    // ElMessage.success(message)
  }

  static error(message: string) {
    console.error(`❌ ${message}`)
    // ElMessage.error(message)
  }

  static warning(message: string) {
    console.warn(`⚠️ ${message}`)
    // ElMessage.warning(message)
  }

  static info(message: string) {
    console.info(`ℹ️ ${message}`)
    // ElMessage.info(message)
  }

  static async confirm(message: string, title = '确认操作'): Promise<boolean> {
    try {
      // 这里可以集成具体的确认对话框组件
      // await ElMessageBox.confirm(message, title, {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning',
      // })
      return window.confirm(`${title}\n${message}`)
    } catch {
      return false
    }
  }
}

// API请求包装器
export class ApiWrapper {
  /**
   * 包装API请求，自动处理加载状态和错误提示
   */
  static async request<T>(
    apiCall: () => Promise<T>,
    options: {
      loadingText?: string
      successMessage?: string
      errorMessage?: string
      showLoading?: boolean
      showSuccess?: boolean
      showError?: boolean
    } = {}
  ): Promise<T | null> {
    const {
      loadingText = '处理中...',
      successMessage,
      errorMessage,
      showLoading = true,
      showSuccess = true,
      showError = true,
    } = options

    try {
      if (showLoading) {
        LoadingManager.show(loadingText)
      }

      const result = await apiCall()

      if (successMessage && showSuccess) {
        MessageUtils.success(successMessage)
      }

      return result
    } catch (error: any) {
      const message = errorMessage || error.message || '操作失败'
      if (showError) {
        MessageUtils.error(message)
      }
      console.error('API请求失败:', error)
      return null
    } finally {
      if (showLoading) {
        LoadingManager.hide()
      }
    }
  }

  /**
   * 包装删除操作，包含确认对话框
   */
  static async deleteWithConfirm<T>(
    apiCall: () => Promise<T>,
    options: {
      confirmMessage?: string
      confirmTitle?: string
      successMessage?: string
      errorMessage?: string
    } = {}
  ): Promise<T | null> {
    const {
      confirmMessage = '确定要删除这条记录吗？此操作不可恢复。',
      confirmTitle = '确认删除',
      successMessage = '删除成功',
      errorMessage = '删除失败',
    } = options

    const confirmed = await MessageUtils.confirm(confirmMessage, confirmTitle)
    if (!confirmed) {
      return null
    }

    return this.request(apiCall, {
      loadingText: '删除中...',
      successMessage,
      errorMessage,
    })
  }

  /**
   * 包装批量删除操作
   */
  static async batchDeleteWithConfirm<T>(
    apiCall: () => Promise<T>,
    count: number,
    options: {
      successMessage?: string
      errorMessage?: string
    } = {}
  ): Promise<T | null> {
    const {
      successMessage = `成功删除 ${count} 条记录`,
      errorMessage = '批量删除失败',
    } = options

    const confirmed = await MessageUtils.confirm(
      `确定要删除选中的 ${count} 条记录吗？此操作不可恢复。`,
      '确认批量删除'
    )
    if (!confirmed) {
      return null
    }

    return this.request(apiCall, {
      loadingText: '批量删除中...',
      successMessage,
      errorMessage,
    })
  }
}

// 数据格式化工具
export class FormatUtils {
  /**
   * 格式化日期
   */
  static formatDate(date: string | Date, format = 'YYYY-MM-DD'): string {
    if (!date) return ''
    const d = new Date(date)
    if (isNaN(d.getTime())) return ''

    const year = d.getFullYear()
    const month = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    const hours = String(d.getHours()).padStart(2, '0')
    const minutes = String(d.getMinutes()).padStart(2, '0')
    const seconds = String(d.getSeconds()).padStart(2, '0')

    return format
      .replace('YYYY', String(year))
      .replace('MM', month)
      .replace('DD', day)
      .replace('HH', hours)
      .replace('mm', minutes)
      .replace('ss', seconds)
  }

  /**
   * 格式化性别
   */
  static formatGender(gender: 'MALE' | 'FEMALE'): string {
    return gender === 'MALE' ? '男' : '女'
  }

  /**
   * 格式化状态
   */
  static formatStatus(status: 'ACTIVE' | 'INACTIVE'): string {
    return status === 'ACTIVE' ? '在职' : '离职'
  }

  /**
   * 格式化手机号
   */
  static formatPhone(phone: string): string {
    if (!phone) return ''
    return phone.replace(/(\d{3})(\d{4})(\d{4})/, '$1-$2-$3')
  }

  /**
   * 获取状态颜色类
   */
  static getStatusColorClass(status: 'ACTIVE' | 'INACTIVE'): string {
    return status === 'ACTIVE' ? 'text-green-600' : 'text-red-600'
  }

  /**
   * 获取性别图标
   */
  static getGenderIcon(gender: 'MALE' | 'FEMALE'): string {
    return gender === 'MALE' ? '👨' : '👩'
  }
}

// 验证工具
export class ValidationUtils {
  /**
   * 验证手机号
   */
  static validatePhone(phone: string): boolean {
    const phoneRegex = /^1[3-9]\d{9}$/
    return phoneRegex.test(phone)
  }

  /**
   * 验证邮箱
   */
  static validateEmail(email: string): boolean {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    return emailRegex.test(email)
  }

  /**
   * 验证身份证号
   */
  static validateIdCard(idCard: string): boolean {
    const idCardRegex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
    return idCardRegex.test(idCard)
  }

  /**
   * 验证年龄
   */
  static validateAge(age: number): boolean {
    return age >= 16 && age <= 70
  }
}

export default {
  LoadingManager,
  MessageUtils,
  ApiWrapper,
  FormatUtils,
  ValidationUtils,
}
